<template>
  <div v-if="loading" class="loading-container">
    <div class="loading-spinner">
      <div class="spinner"></div>
      <div class="loading-text">正在加载数据...</div>
    </div>
  </div>
  <div class="workbench">
    <h2 class="workbench-title">工作台</h2>

    <!-- 核心指标 -->
    <div class="core-indicators">
      <div class="indicators-header">
        <span class="date-info">{{ currentDate }}</span>
      </div>
      <div class="indicators-grid">
        <div v-for="indicator in currentIndicators" :key="indicator.key" class="indicator-card">
          <div class="indicator-icon" :class="indicator.iconClass">
            {{ indicator.icon }}
          </div>
          <div class="indicator-content">
            <div class="indicator-label">{{ indicator.label }}</div>
            <div class="indicator-value">{{ indicator.value }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计图表 -->
    <div class="statistics-section">
      <div class="statistics-header">
        <div class="statistics-tabs">
          <div class="tab-item" :class="{ active: activeStatsTab === 'sales' }"
            @click="switchStatsTab('sales')">
            销售统计
          </div>
          <div class="tab-item" :class="{ active: activeStatsTab === 'purchase' }"
            @click="switchStatsTab('purchase')">
            采购统计
          </div>
        </div>
        <div class="time-range">
          <el-button v-for="timeRange in timeRanges" :key="timeRange.key" class="time-btn"
            :class="{ active: activeTimeRange === timeRange.key }"
            @click="switchTimeRange(timeRange.key)">
            {{ timeRange.label }}
          </el-button>
        </div>
      </div>

      <div class="chart-container">
        <div class="chart-legend">
          <div class="legend-item">
            <div class="legend-color"
              :class="activeStatsTab === 'sales' ? 'order-amount-sales' : 'order-amount-purchase'">
            </div>
            <span>订单额</span>
          </div>
          <div class="legend-item">
            <div class="legend-color"
              :class="activeStatsTab === 'sales' ? 'order-count-sales' : 'order-count-purchase'">
            </div>
            <span>订单数</span>
          </div>
        </div>

        <div class="chart" ref="chartRef"></div>
      </div>
    </div>

    <!-- 待审批单据和通知公告 -->
    <div class="bottom-sections">
      <div class="left-section">
        <!-- 待审批单据 -->
        <div class="approval-section">
          <div class="section-header">
            <h3 class="section-title">待审批单据</h3>
            <button class="refresh-btn" @click="refreshApprovalData" :disabled="loading" title="刷新数据">
              <span class="refresh-icon" :class="{ 'rotating': loading }">🔄</span>
            </button>
          </div>
          <div class="approval-grid">
            <div v-for="item in approvalItems" :key="item.key" class="approval-item">
              <div class="approval-icon" :class="item.iconClass">
                {{ item.icon }}
              </div>
              <div class="approval-content">
                <div class="approval-label">{{ item.label }}</div>
                <div class="approval-count">{{ item.count }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="right-section">
        <!-- 通知公告 -->
        <div class="announcement-section">
          <h3 class="section-title">通知公告</h3>
          <div class="announcement-table">
            <table>
              <thead>
                <tr>
                  <th>公告内容</th>
                  <th>发布时间</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="announcement in announcements" :key="announcement.id">
                  <td>{{ announcement.content }}</td>
                  <td>{{ formatDateTime(announcement.createTime) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单交付提醒 -->
    <div class="delivery-reminder-section">
      <div class="reminder-header">
        <div class="reminder-tabs">
          <div v-for="tab in reminderTabs" :key="tab.key" class="reminder-tab"
            :class="{ active: activeReminderTab === tab.key }"
            @click="switchReminderTab(tab.key)">
            {{ tab.label }}
          </div>
        </div>
      </div>

      <div class="reminder-table">
        <table>
          <thead>
            <tr>
              <th v-for="col in currentTableColumns" :key="col.key">{{ col.label }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in currentReminderItems" :key="item.id">
              <td v-for="col in currentTableColumns" :key="col.key">
                <template v-if="col.key === 'operation'">
                  <el-button type="text" size="small" @click="viewDocument(item)">
                    查看
                  </el-button>
                </template>
                <template v-else-if="isTimeField(col.key)">
                  {{ formatDateTime(item[col.key]) }}
                </template>
                <template v-else>
                  {{ item[col.key] }}
                </template>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 如果没有数据，显示提示 -->
        <div v-if="currentReminderItems.length === 0"
          style="text-align: center; padding: 20px; color: #999;">
          当前标签页没有数据
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { consoleApi } from '@/services/console'
import moment from 'moment'
import type {
  CoreMetricsDto,
  StatisticsDto,
  AnnouncementDto,
  ApprovalDocumentDto,
  ProductionSalesOrderDto,
  ProductionOrderDto,
  ProcessDto,
  ProductionItemDto,
  ChartDataDto
} from '@/types/console'

const chartRef = ref<HTMLElement>()

// 格式化工具函数
const formatDateTime = (date: string | Date | null | undefined, format: string = 'YYYY-MM-DD HH:mm:ss'): string => {
  if (!date) return '未设置'
  try {
    return moment(date).format(format)
  } catch (error) {
    console.warn('日期格式化失败:', error, '原始值:', date)
    return '无效日期'
  }
}

const formatPrice = (price: number | string | null | undefined): string => {
  if (price === null || price === undefined || price === '') return '¥0.00'
  try {
    const numPrice = typeof price === 'string' ? parseFloat(price) : price
    if (isNaN(numPrice)) return '¥0.00'
    return `¥${numPrice.toFixed(2)}`
  } catch (error) {
    console.warn('价格格式化失败:', error, '原始值:', price)
    return '¥0.00'
  }
}

const formatQuantity = (quantity: number | string | null | undefined, unit: string = ''): string => {
  if (quantity === null || quantity === undefined || quantity === '') return `0${unit}`
  try {
    const numQuantity = typeof quantity === 'string' ? parseFloat(quantity) : quantity
    if (isNaN(numQuantity)) return `0${unit}`
    return Number.isInteger(numQuantity) ? `${numQuantity}${unit}` : `${numQuantity.toFixed(2)}${unit}`
  } catch (error) {
    console.warn('数量格式化失败:', error, '原始值:', quantity)
    return `0${unit}`
  }
}

// 判断是否为时间字段
const isTimeField = (fieldKey: string): boolean => {
  const timeFields = [
    'createTime', 'updateTime', 'deliveryDate', 'plannedStartTime',
    'plannedIntroTime', 'actualStartTime', 'actualCompletionTime',
    'productionDate', 'expiryDate', 'publishTime', 'expiryTime',
    'applicationTime', 'approvalTime'
  ]
  return timeFields.includes(fieldKey)
}

// 响应式状态
const activeStatsTab = ref('sales')
const activeTimeRange = ref('week')
const activeReminderTab = ref('order-delivery')

// 待审批单据数据
const approvalItems = ref([
  { key: 'purchase-order', label: '采购订单', count: 0, icon: '📋', iconClass: 'approval-icon purchase' },
  { key: 'sales-order', label: '销售订单', count: 0, icon: '📄', iconClass: 'approval-icon sales' },
  { key: 'inbound-receipt', label: '入库单', count: 0, icon: '📥', iconClass: 'approval-icon inbound' },
  { key: 'outbound-receipt', label: '出库单', count: 0, icon: '📤', iconClass: 'approval-icon outbound' },
  { key: 'invoice-receipt', label: '到票单', count: 0, icon: '🧾', iconClass: 'approval-icon invoice' },
  { key: 'expense-voucher', label: '支出单', count: 0, icon: '💰', iconClass: 'approval-icon expense' },
  { key: 'invoice-issuance', label: '开票单', count: 0, icon: '📊', iconClass: 'approval-icon issuance' },
  { key: 'requisition-form', label: '请购单', count: 0, icon: '📝', iconClass: 'approval-icon requisition' }
])

// 强制更新函数
const updateApprovalCounts = () => {
  approvalItems.value.forEach(item => {
    let count = 0

    // 方法1：直接匹配 documentType
    count = approvalDocuments.value.filter(doc =>
      doc.documentType === item.key && doc.status === '待审批'
    ).length

    // 方法2：如果上面没有匹配到，尝试模糊匹配
    if (count === 0) {
      count = approvalDocuments.value.filter(doc => {
        const docType = doc.documentType?.toLowerCase() || ''
        const itemKey = item.key.toLowerCase()
        return (docType.includes(itemKey) || itemKey.includes(docType)) && doc.status === '待审批'
      }).length
    }

    // 方法3：尝试匹配销售订单数据（因为后端返回的是销售订单，不是审批单据）
    if (count === 0 && item.key === 'sales-order') {
      count = salesOrders.value.filter(order =>
        order.status === '已下单' || order.status === '待审批' || order.status === '处理中'
      ).length
    }

    // 方法4：尝试匹配采购订单数据
    if (count === 0 && item.key === 'purchase-order') {
      // 从审批单据中查找采购相关的
      count = approvalDocuments.value.filter(doc => {
        const docType = doc.documentType?.toLowerCase() || ''
        return (docType.includes('采购') || docType.includes('purchase')) &&
          ['待审批', '处理中', '已下单'].includes(doc.status)
      }).length
    }

    // 方法5：如果还是没有，尝试状态匹配（包括所有非已完成状态）
    if (count === 0) {
      count = approvalDocuments.value.filter(doc => {
        const docType = doc.documentType?.toLowerCase() || ''
        const itemKey = item.key.toLowerCase()
        const isMatchingType = docType.includes(itemKey) || itemKey.includes(docType)
        const isPendingStatus = ['待审批', '处理中', '已下单', '已驳回'].includes(doc.status)
        return isMatchingType && isPendingStatus
      }).length
    }

    item.count = count
  })

  // 强制触发响应式更新
  approvalItems.value = [...approvalItems.value]
}

// 通知公告数据
const announcements = ref<AnnouncementDto[]>([])

// 核心指标数据
const coreMetrics = ref<CoreMetricsDto | null>(null)

// 统计数据
const statisticsData = ref<StatisticsDto[]>([])

// 审批单据数据
const approvalDocuments = ref<ApprovalDocumentDto[]>([])

// 销售订单数据
const salesOrders = ref<ProductionSalesOrderDto[]>([])

// 生产工单数据
const productionOrders = ref<ProductionOrderDto[]>([])

// 工序数据
const processes = ref<ProcessDto[]>([])

// 生产物品数据
const productionItems = ref<ProductionItemDto[]>([])

// 加载状态
const loading = ref(false)

// 缓存管理
const cacheExpiry = ref<Record<string, number>>({})
const CACHE_DURATION = 1 * 60 * 1000 // 修改：缩短为1分钟缓存过期

// 工作台切换和刷新相关状态
const switching = ref(false)
const refreshing = ref(false)
const autoRefresh = ref(false)
const refreshInterval = ref('30') // 修改：默认30秒自动刷新
let refreshTimer: number | null = null

// 检查缓存是否过期
const isCacheExpired = (key: string): boolean => {
  const expiryTime = cacheExpiry.value[key]
  if (!expiryTime) return true
  return Date.now() > expiryTime
}

// 设置缓存过期时间
const setCacheExpiry = (key: string) => {
  cacheExpiry.value[key] = Date.now() + CACHE_DURATION
}

// 清除缓存
const clearCache = (key?: string) => {
  if (key) {
    delete cacheExpiry.value[key]
  } else {
    cacheExpiry.value = {}
  }
}

// 强制刷新数据（跳过缓存）
const forceRefreshData = async () => {
  if (refreshing.value) return

  refreshing.value = true
  try {
    // 清除所有缓存，强制重新获取数据
    clearCache()

    // 重新加载数据
    await loadDashboardData(true) // 传入强制刷新标志

    // 重新初始化图表
    if (chart) {
      updateChart()
    }

    console.log('强制刷新完成')
  } catch (error) {
    console.error('强制刷新失败:', error)
  } finally {
    refreshing.value = false
  }
}

// 自动刷新管理
const startAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }

  const interval = parseInt(refreshInterval.value) * 1000
  refreshTimer = setInterval(() => {
    refreshData()
  }, interval)
}

const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 刷新数据函数
const refreshData = async () => {
  if (refreshing.value) return

  refreshing.value = true
  try {
    // 清除所有缓存，强制重新获取数据
    clearCache()

    // 重新加载数据
    await loadDashboardData()

    // 重新初始化图表
    if (chart) {
      updateChart()
    }

    console.log('数据刷新完成')
  } catch (error) {
    console.error('数据刷新失败:', error)
  } finally {
    refreshing.value = false
  }
}

// 处理自动刷新开关变化
const handleAutoRefreshChange = (value: boolean) => {
  if (value) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
}

// 处理刷新间隔变化
const handleRefreshIntervalChange = (value: string) => {
  if (autoRefresh.value) {
    startAutoRefresh()
  }
}

// 提醒标签页
const reminderTabs = [
  { key: 'order-delivery', label: '订单交付提醒' },
  { key: 'work-order', label: '工单提醒' },
  { key: 'process', label: '工序提醒' },
  { key: 'expiring-items', label: '即将到期物品' },
  { key: 'expired-items', label: '已到期物品' }
]

// 动态提醒数据
const reminderData = computed(() => {
  const data = {
    'order-delivery': salesOrders.value.filter(order => {
      const isPending = ['已下单', '待交付', '处理中'].includes(order.status)
      return isPending
    }),
    'work-order': productionOrders.value.filter(order => {
      const isActive = ['开工', '进行中', '待开始'].includes(order.status)
      return isActive
    }),
    'process': processes.value.filter(process => {
      const isActive = ['已下发', '进行中', '待开始'].includes(process.status)
      return isActive
    }),
    'expiring-items': productionItems.value.filter(item => {
      if (!item.expiryDate) return false

      try {
        const expiryDate = new Date(item.expiryDate)
        const now = new Date()

        if (isNaN(expiryDate.getTime())) {
          return false
        }

        const diffTime = expiryDate.getTime() - now.getTime()
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

        // 显示所有未过期的物品
        return diffDays > 0

      } catch (error) {
        return false
      }
    }),
    'expired-items': productionItems.value.filter(item => {
      if (!item.expiryDate) return false
      const expiryDate = new Date(item.expiryDate)
      const now = new Date()
      const isExpired = expiryDate < now
      return isExpired
    })
  }

  return data
})

// 表格列配置
const tableColumns: Record<string, Array<{ key: string; label: string }>> = {
  'order-delivery': [
    { key: 'orderNumber', label: '单据单号' },
    { key: 'subject', label: '单据主题' },
    { key: 'orderType', label: '单据类型' },
    { key: 'status', label: '单据状态' },
    { key: 'deliveryDate', label: '交付日期' },
    { key: 'operation', label: '操作' }
  ],
  'work-order': [
    { key: 'orderNumber', label: '单据单号' },
    { key: 'productionItem', label: '生产物品' },
    { key: 'status', label: '单据状态' },
    { key: 'plannedStartTime', label: '计划开始时间' },
    { key: 'plannedIntroTime', label: '计划介绍时间' },
    { key: 'responsiblePerson', label: '负责人' },
    { key: 'operation', label: '操作' }
  ],
  'process': [
    { key: 'documentNumber', label: '单据单号' },
    { key: 'processName', label: '工序名称' },
    { key: 'status', label: '状态' },
    { key: 'plannedStartTime', label: '计划开始时间' },
    { key: 'plannedIntroTime', label: '计划介绍时间' },
    { key: 'responsiblePerson', label: '负责人' },
    { key: 'operation', label: '操作' }
  ],
  'expiring-items': [
    { key: 'itemNumber', label: '物品编号' },
    { key: 'itemName', label: '物品名称' },
    { key: 'batchNumber', label: '批次号' },
    { key: 'productionDate', label: '生产日期' },
    { key: 'expiryDate', label: '到期日期' },
    { key: 'warehouseName', label: '仓库' },
    { key: 'inventoryQuantity', label: '库存数量' },
    { key: 'operation', label: '操作' }
  ],
  'expired-items': [
    { key: 'itemNumber', label: '物品编号' },
    { key: 'itemName', label: '物品名称' },
    { key: 'batchNumber', label: '批次号' },
    { key: 'productionDate', label: '生产日期' },
    { key: 'expiryDate', label: '到期日期' },
    { key: 'warehouseName', label: '仓库' },
    { key: 'inventoryQuantity', label: '库存数量' },
    { key: 'operation', label: '操作' }
  ]
}

// 计算属性
const currentReminderItems = computed(() => {
  return (reminderData.value as any)[activeReminderTab.value] || []
})

const currentTableColumns = computed(() => {
  return tableColumns[activeReminderTab.value] || []
})

// 时间范围选项
const timeRanges = [
  { key: 'week', label: '最近1周' },
  { key: 'month', label: '最近30天' },
  { key: 'year', label: '最近1年' }
]

const currentDate = computed(() => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const weekday = weekdays[now.getDay()]
  return `${year}-${month}-${day} ${weekday}`
})

const currentIndicators = computed(() => {
  if (!coreMetrics.value) {
    return [
      { key: 'sales-revenue', label: '今日销售收入(元)', value: '0.00', icon: '¥', iconClass: 'revenue-icon' },
      { key: 'sales-orders', label: '今日销售订单量(笔)', value: '0', icon: '📄', iconClass: 'order-icon' },
      { key: 'collection', label: '今日回款(元)', value: '0.00', icon: '↓', iconClass: 'collection-icon' },
      { key: 'purchase-expense', label: '今日采购支出(元)', value: '0.00', icon: '¥', iconClass: 'purchase-icon' },
      { key: 'purchase-orders', label: '今日采购订单(笔)', value: '0', icon: '📄', iconClass: 'purchase-order-icon' },
      { key: 'paid-amount', label: '今日已付款(元)', value: '0.00', icon: '↑', iconClass: 'payment-icon' }
    ]
  }

  const baseIndicators = [
    { key: 'sales-revenue', label: '今日销售收入(元)', value: formatPrice(coreMetrics.value.salesRevenue), icon: '¥', iconClass: 'revenue-icon' },
    { key: 'sales-orders', label: '今日销售订单量(笔)', value: coreMetrics.value.salesOrderCount.toString(), icon: '📄', iconClass: 'order-icon' },
    { key: 'collection', label: '今日回款(元)', value: formatPrice(coreMetrics.value.collection), icon: '↓', iconClass: 'collection-icon' },
    { key: 'purchase-expense', label: '今日采购支出(元)', value: formatPrice(coreMetrics.value.purchaseExpense), icon: '¥', iconClass: 'purchase-icon' },
    { key: 'purchase-orders', label: '今日采购订单(笔)', value: coreMetrics.value.purchaseOrderCount.toString(), icon: '📄', iconClass: 'purchase-order-icon' },
    { key: 'paid-amount', label: '今日已付款(元)', value: formatPrice(coreMetrics.value.paidAmount), icon: '↑', iconClass: 'payment-icon' }
  ]

  return baseIndicators
})

// 事件处理函数
const switchStatsTab = (tabKey: string) => {
  activeStatsTab.value = tabKey
  updateChart()
}

const switchTimeRange = (timeKey: string) => {
  activeTimeRange.value = timeKey
  updateChart()
}

const switchReminderTab = (tabKey: string) => {
  activeReminderTab.value = tabKey
}

const viewDocument = (item: any) => {
  // 实际应用中可以跳转到详情页面或弹出模态框
}

// 图表相关
let chart: echarts.ECharts | null = null

// 生成时间标签的函数
const generateTimeLabels = (timeRange: string): string[] => {
  const today = new Date()
  const labels: string[] = []

  switch (timeRange) {
    case 'week':
      // 往前推7天，最后一天是今天
      for (let i = 6; i >= 0; i--) {
        const date = new Date(today)
        date.setDate(today.getDate() - i)
        const month = date.getMonth() + 1
        const day = date.getDate()
        labels.push(`${month}/${day}`)
      }
      break
    case 'month':
      // 往前推31天，最后一天是今天
      for (let i = 30; i >= 0; i--) {
        const date = new Date(today)
        date.setDate(today.getDate() - i)
        const month = date.getMonth() + 1
        const day = date.getDate()
        labels.push(`${month}/${day}`)
      }
      break
    case 'year':
      // 往前推12个月，最后一个月是当前月
      for (let i = 11; i >= 0; i--) {
        const date = new Date(today)
        date.setMonth(today.getMonth() - i)
        const month = date.getMonth() + 1
        labels.push(`${month}月`)
      }
      break
    default:
      labels.push('今天')
  }

  return labels
}

// 图表数据配置
const chartData: Record<string, Record<string, { orderAmount: number[]; orderCount: number[]; timeLabels: string[] }>> = {
  sales: {
    'week': {
      orderAmount: [450, 420, 300, 320, 220, 180, 550],
      orderCount: [20, 25, 40, 55, 35, 20, 45],
      timeLabels: generateTimeLabels('week')
    },
    'month': {
      orderAmount: Array.from({ length: 31 }, () => Math.floor(Math.random() * 500 + 100)),
      orderCount: Array.from({ length: 31 }, () => Math.floor(Math.random() * 50 + 10)),
      timeLabels: generateTimeLabels('month')
    },
    'year': {
      orderAmount: [450, 420, 300, 320, 220, 180, 550, 380, 420, 500, 280, 400],
      orderCount: [20, 25, 40, 55, 35, 20, 45, 30, 35, 50, 25, 40],
      timeLabels: generateTimeLabels('year')
    }
  },
  purchase: {
    'week': {
      orderAmount: [320, 280, 450, 380, 290, 420, 350],
      orderCount: [15, 22, 38, 42, 28, 35, 30],
      timeLabels: generateTimeLabels('week')
    },
    'month': {
      orderAmount: Array.from({ length: 31 }, () => Math.floor(Math.random() * 500 + 100)),
      orderCount: Array.from({ length: 31 }, () => Math.floor(Math.random() * 50 + 10)),
      timeLabels: generateTimeLabels('month')
    },
    'year': {
      orderAmount: [10, 520, 220, 440, 120, 560, 20, 320, 370, 160, 490, 470],
      orderCount: [15, 12, 18, 55, 40, 30, 5, 48, 35, 22, 52, 35],
      timeLabels: generateTimeLabels('year')
    }
  }
}

// 数据加载函数
const loadDashboardData = async (forceRefresh = false) => {
  // 检查缓存是否过期（强制刷新时跳过缓存检查）
  if (!forceRefresh && !isCacheExpired('dashboard')) {
    console.log('使用缓存数据')
    return
  }

  loading.value = true
  try {
    // 并行加载所有数据
    const [
      coreMetricsResult,
      announcementsResult,
      approvalDocumentsResult,
      approvalStatisticsResult,
      salesOrdersResult,
      productionOrdersResult,
      processesResult,
      productionItemsResult
    ] = await Promise.all([
      consoleApi.getTodayMetrics(), // 修改：使用今日核心指标API
      consoleApi.getAnnouncements({ pageIndex: 1, pageSize: 10 }),
      consoleApi.getApprovalDocuments({ pageIndex: 1, pageSize: 100 }),
      consoleApi.getApprovalStatistics(), // 新增：获取待审批单据统计
      consoleApi.getSalesOrders({ pageIndex: 1, pageSize: 100 }),
      consoleApi.getProductionOrders({ pageIndex: 1, pageSize: 100 }),
      consoleApi.getProcesses({ pageIndex: 1, pageSize: 100 }),
      consoleApi.getProductionItems({ pageIndex: 1, pageSize: 100 })
    ])

    // 处理核心指标
    if (coreMetricsResult.code === 200 && coreMetricsResult.data) {
      coreMetrics.value = coreMetricsResult.data // 直接使用返回的数据
    } else {
      // 设置默认的核心指标数据
      coreMetrics.value = {
        id: 1,
        date: new Date().toISOString(),
        salesRevenue: 12500.00,
        salesOrderCount: 45,
        collection: 8900.00,
        purchaseExpense: 15600.00,
        purchaseOrderCount: 32,
        paidAmount: 12300.00,
        remarks: '默认数据'
      }
    }

    // 处理通知公告
    if (announcementsResult.code === 200 && announcementsResult.data && announcementsResult.data.items.length > 0) {
      announcements.value = announcementsResult.data.items
    } else {
      // 设置默认的通知公告数据
      announcements.value = [
        {
          id: 1,
          content: '年度总结会议将于下月召开',
          type: '会议通知',
          priority: 1,
          isActive: true,
          publishTime: '2024-01-24',
          expiryTime: '2024-12-31',
          publisher: '系统管理员',
          targetUserGroup: '全体员工',
          remarks: '重要会议通知',
          createTime: '2024-01-24 09:00:00',
          creator: '系统管理员'
        },
        {
          id: 2,
          content: '环保检查通知：环保局将于下月初进行检查',
          type: '检查通知',
          priority: 2,
          isActive: true,
          publishTime: '2024-01-23',
          expiryTime: '2024-02-15',
          publisher: '环保部门',
          targetUserGroup: '生产部门',
          remarks: '环保检查',
          createTime: '2024-01-23 14:30:00',
          creator: '环保部门'
        },
        {
          id: 3,
          content: '库存盘点将于月底进行，请提前准备',
          type: '工作通知',
          priority: 1,
          isActive: true,
          publishTime: '2024-01-22',
          expiryTime: '2024-01-31',
          publisher: '仓库管理员',
          targetUserGroup: '仓库部门',
          remarks: '月度盘点',
          createTime: '2024-01-22 10:15:00',
          creator: '仓库管理员'
        }
      ]
    }

    // 处理审批单据
    if (approvalDocumentsResult.code === 200 && approvalDocumentsResult.data && approvalDocumentsResult.data.items.length > 0) {
      approvalDocuments.value = approvalDocumentsResult.data.items
    } else {
      // 设置默认的审批单据数据
      approvalDocuments.value = [
        {
          id: 1,
          documentType: 'sales-order',
          documentId: 1001,
          documentNumber: 'XSDH202401001',
          status: '待审批',
          priority: 1,
          applicant: '销售员张三',
          applicationTime: '2024-01-24 08:30:00',
          approver: undefined,
          approvalTime: undefined,
          approvalComments: undefined,
          remarks: '大客户订单',
          createTime: '2024-01-24 08:30:00',
          creator: '销售员张三'
        },
        {
          id: 2,
          documentType: 'purchase-order',
          documentId: 2001,
          documentNumber: 'CGDH202401001',
          status: '待审批',
          priority: 2,
          applicant: '采购员李四',
          applicationTime: '2024-01-24 09:15:00',
          approver: undefined,
          approvalTime: undefined,
          approvalComments: undefined,
          remarks: '原材料采购',
          createTime: '2024-01-24 09:15:00',
          creator: '采购员李四'
        }
      ]
    }

    // 处理待审批单据统计
    if (approvalStatisticsResult.code === 200 && approvalStatisticsResult.data) {
      const stats = approvalStatisticsResult.data
      
      // 更新待审批单据数量
      approvalItems.value.forEach(item => {
        switch (item.key) {
          case 'purchase-order':
            item.count = stats.purchaseOrder || 0
            break
          case 'sales-order':
            item.count = stats.salesOrder || 0
            break
          case 'inbound-receipt':
            item.count = stats.inboundReceipt || 0
            break
          case 'outbound-receipt':
            item.count = stats.outboundReceipt || 0
            break
          case 'invoice-receipt':
            item.count = stats.invoiceReceipt || 0
            break
          case 'expense-voucher':
            item.count = stats.expenseVoucher || 0
            break
          case 'invoice-issuance':
            item.count = stats.invoiceIssuance || 0
            break
          case 'requisition-form':
            item.count = stats.requisitionForm || 0
            break
        }
      })
      
      console.log('待审批单据统计已更新:', stats)
    } else {
      // 如果API失败，使用原有的更新逻辑
      updateApprovalCounts()
    }

    // 处理销售订单
    if (salesOrdersResult.code === 200 && salesOrdersResult.data && salesOrdersResult.data.items.length > 0) {
      salesOrders.value = salesOrdersResult.data.items

    } else {
      // 设置默认的销售订单数据
      salesOrders.value = [
        {
          id: 1,
          orderNumber: 'XSDH202401001',
          subject: '新产品销售订单001',
          orderType: '销售订单',
          status: '待交付',
          deliveryDate: '2024-02-15',
          totalAmount: 25000.00,
          customerId: 1001,
          customerName: 'ABC公司',
          remarks: '大客户订单',
          createTime: '2024-01-24 08:30:00',
          creator: '销售员张三'
        },
        {
          id: 2,
          orderNumber: 'XSDH202401002',
          subject: '新产品销售订单002',
          orderType: '销售订单',
          status: '待交付',
          deliveryDate: '2024-02-20',
          totalAmount: 18000.00,
          customerId: 1002,
          customerName: 'XYZ公司',
          remarks: '标准订单',
          createTime: '2024-01-24 10:00:00',
          creator: '销售员李四'
        }
      ]
    }

    // 处理生产工单
    if (productionOrdersResult.code === 200 && productionOrdersResult.data && productionOrdersResult.data.items.length > 0) {
      productionOrders.value = productionOrdersResult.data.items

    } else {
      // 设置默认的生产工单数据
      productionOrders.value = [
        {
          id: 1,
          orderNumber: 'SCGD202401001',
          subject: '新产品生产工单001',
          orderType: '生产工单',
          productionItem: '新产品A',  // 添加缺失的必需属性
          status: '进行中',
          plannedStartTime: '2024-01-25 08:00:00',
          plannedCompletionTime: '2024-01-30 17:00:00',
          actualStartTime: '2024-01-25 08:30:00',
          actualCompletionTime: undefined,
          plannedQuantity: 100,  // 添加缺失的必需属性
          totalQuantity: 100,
          completedQuantity: 45,
          actualQuantity: 45,  // 添加缺失的必需属性
          priority: 1,  // 添加缺失的必需属性
          remarks: '标准生产工单',
          createTime: '2024-01-24 14:00:00',
          creator: '生产计划员'
        }
      ]
    }

    // 处理工序数据
    if (processesResult.code === 200 && processesResult.data && processesResult.data.items.length > 0) {
      processes.value = processesResult.data.items
    } else {
      // 设置默认的工序数据
      processes.value = [
        {
          id: 1,
          documentNumber: 'QG001',  // 添加缺失的必需属性
          processName: '切割工序',
          processCode: 'QG001',
          processType: '机械加工',
          standardTime: 30,
          unit: '分钟',
          status: '进行中',  // 添加缺失的必需属性
          priority: 1,  // 添加缺失的必需属性
          remarks: '标准切割工序',
          createTime: '2024-01-24 10:00:00',
          creator: '工艺工程师'
        }
      ]
    }

    // 处理生产物品数据
    if (productionItemsResult.code === 200 && productionItemsResult.data && productionItemsResult.data.items.length > 0) {
      productionItems.value = productionItemsResult.data.items
    } else {
      // 设置默认的生产物品数据
      productionItems.value = [
        {
          id: 1,
          itemNumber: 'SCWP001',
          itemName: '新产品A',
          itemType: '成品',
          unit: '件',
          standardCost: 150.00,
          inventoryQuantity: 100,  // 添加缺失的必需属性
          remarks: '主要产品',
          createTime: '2024-01-24 11:00:00',
          creator: '产品工程师'
        }
      ]
    }

    // 设置缓存过期时间
    setCacheExpiry('dashboard')

    // 强制更新图表
    if (chart) {
      updateChart()
    }

  } catch (error) {
    console.error('加载控制台数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 刷新待审批单据数据
const refreshApprovalData = async () => {
  try {
    loading.value = true
    console.log('开始刷新待审批单据数据...')
    
    // 获取最新的待审批单据统计数据
    const approvalStatisticsResult = await consoleApi.getApprovalStatistics()
    
    if (approvalStatisticsResult.code === 200 && approvalStatisticsResult.data) {
      const stats = approvalStatisticsResult.data
      
      // 更新待审批单据数量
      approvalItems.value.forEach(item => {
        switch (item.key) {
          case 'purchase-order':
            item.count = stats.purchaseOrder || 0
            break
          case 'sales-order':
            item.count = stats.salesOrder || 0
            break
          case 'inbound-receipt':
            item.count = stats.inboundReceipt || 0
            break
          case 'outbound-receipt':
            item.count = stats.outboundReceipt || 0
            break
          case 'invoice-receipt':
            item.count = stats.invoiceReceipt || 0
            break
          case 'expense-voucher':
            item.count = stats.expenseVoucher || 0
            break
          case 'invoice-issuance':
            item.count = stats.invoiceIssuance || 0
            break
          case 'requisition-form':
            item.count = stats.requisitionForm || 0
            break
        }
      })
      
      console.log('待审批单据数据刷新成功:', stats)
    } else {
      console.error('刷新待审批单据数据失败:', approvalStatisticsResult.msg)
    }
  } catch (error) {
    console.error('刷新待审批单据数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 初始化图表函数
const initChart = () => {
  if (!chartRef.value) return

  // 如果图表已存在，先销毁
  if (chart) {
    chart.dispose()
  }

  // 重新初始化图表
  chart = echarts.init(chartRef.value)

  // 更新图表
  updateChart()

  // 响应式调整
  window.addEventListener('resize', () => {
    chart?.resize()
  })
}

const updateChart = async () => {
  if (!chart) return

  try {
    let apiChartData: ChartDataDto | null = null

    // 根据当前选中的标签页和时间范围获取真实数据
    if (activeStatsTab.value === 'sales') {
      const response = await consoleApi.getSalesChartData(activeTimeRange.value)

      if (response.code === 200 && response.data) {
        apiChartData = response.data
      }
    } else if (activeStatsTab.value === 'purchase') {
      const response = await consoleApi.getPurchaseChartData(activeTimeRange.value)

      if (response.code === 200 && response.data) {
        apiChartData = response.data
      }
    }



    // 简化数据处理逻辑 - 返回啥给啥
    let orderAmount: number[] = []
    let orderCount: number[] = []
    let timeLabels: string[] = []

    // 直接使用API返回的数据，不做严格验证
    if (apiChartData) {
      orderAmount = (apiChartData.orderAmounts || []).map((amount: any) => Number(amount) || 0)
      orderCount = (apiChartData.orderCounts || []).map((count: any) => Number(count) || 0)
      timeLabels = apiChartData.TimeLabels || []
    }

    // 如果时间标签为空，使用前端生成的标签
    if (timeLabels.length === 0) {
      timeLabels = generateTimeLabels(activeTimeRange.value)
    }

    // 确保数据长度一致，避免图表显示异常
    const maxLength = Math.max(timeLabels.length, orderAmount.length, orderCount.length)

    // 如果时间标签不足，使用前端生成的标签
    if (timeLabels.length < maxLength) {
      timeLabels = generateTimeLabels(activeTimeRange.value)
    }

    // 如果数据不足，填充默认值
    if (orderAmount.length < maxLength) {
      const padding = Array.from({ length: maxLength - orderAmount.length }, () => 0)
      orderAmount = [...orderAmount, ...padding]
    }
    if (orderCount.length < maxLength) {
      const padding = Array.from({ length: maxLength - orderCount.length }, () => 0)
      orderCount = [...orderCount, ...padding]
    }

    // 截取到相同长度
    timeLabels = timeLabels.slice(0, maxLength)
    orderAmount = orderAmount.slice(0, maxLength)
    orderCount = orderCount.slice(0, maxLength)



    // 设置图表选项
    const option = {
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: timeLabels.length > 0 ? timeLabels : generateTimeLabels(activeTimeRange.value),
        axisLine: {
          lineStyle: {
            color: '#ddd'
          }
        },
        axisLabel: {
          color: '#666'
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '单位 (元)',
          position: 'left',
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisLabel: {
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              color: '#f0f0f0'
            }
          }
        },
        {
          type: 'value',
          name: '单位 (笔)',
          position: 'right',
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisLabel: {
            color: '#666'
          },
          splitLine: {
            show: false
          }
        }
      ],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function (params: any) {
          let result = params[0].axisValue + '<br/>'
          params.forEach((param: any) => {
            if (param.seriesName === '订单额') {
              result += param.marker + param.seriesName + ': ' + formatPrice(param.value) + '<br/>'
            } else {
              result += param.marker + param.seriesName + ': ' + param.value + '<br/>'
            }
          })
          return result
        }
      },
      legend: {
        data: ['订单额', '订单数'],
        top: '2%',
        textStyle: {
          color: '#666'
        }
      },
      series: [
        {
          name: '订单额',
          type: 'bar',
          yAxisIndex: 0,
          data: orderAmount,
          itemStyle: {
            color: activeStatsTab.value === 'sales' ? '#409EFF' : '#20B2AA'
          }
        },
        {
          name: '订单数',
          type: 'line',
          yAxisIndex: 1,
          data: orderCount,
          itemStyle: {
            color: activeStatsTab.value === 'sales' ? '#67C23A' : '#9370DB'
          },
          lineStyle: {
            color: activeStatsTab.value === 'sales' ? '#67C23A' : '#9370DB'
          },
          symbol: 'circle',
          symbolSize: 6
        }
      ]
    }

    chart.setOption(option)
  } catch (error) {
    console.error('更新图表失败:', error)
    // 如果API调用失败，使用默认数据
    try {
      const currentData = chartData[activeStatsTab.value]?.[activeTimeRange.value]
      if (currentData) {
        const orderAmount = currentData.orderAmount
        const orderCount = currentData.orderCount
        const timeLabels = currentData.timeLabels

        // 设置默认图表选项
        const defaultOption = {
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: timeLabels.length > 0 ? timeLabels : generateTimeLabels(activeTimeRange.value),
            axisLine: {
              lineStyle: {
                color: '#ddd'
              }
            },
            axisLabel: {
              color: '#666'
            }
          },
          yAxis: [
            {
              type: 'value',
              name: '单位 (元)',
              position: 'left',
              axisLine: {
                lineStyle: {
                  color: '#ddd'
                }
              },
              axisLabel: {
                color: '#666'
              },
              splitLine: {
                lineStyle: {
                  color: '#f0f0f0'
                }
              }
            },
            {
              type: 'value',
              name: '单位 (笔)',
              position: 'right',
              axisLine: {
                lineStyle: {
                  color: '#ddd'
                }
              },
              axisLabel: {
                color: '#666'
              },
              splitLine: {
                show: false
              }
            }
          ],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            },
            formatter: function (params: any) {
              let result = params[0].axisValue + '<br/>'
              params.forEach((param: any) => {
                if (param.seriesName === '订单额') {
                  result += param.marker + param.seriesName + ': ' + formatPrice(param.value) + '<br/>'
                } else {
                  result += param.marker + param.seriesName + ': ' + param.value + '<br/>'
                }
              })
              return result
            }
          },
          legend: {
            data: ['订单额', '订单数'],
            top: '2%',
            textStyle: {
              color: '#666'
            }
          },
          series: [
            {
              name: '订单额',
              type: 'bar',
              yAxisIndex: 0,
              data: orderAmount,
              itemStyle: {
                color: activeStatsTab.value === 'sales' ? '#409EFF' : '#20B2AA'
              }
            },
            {
              name: '订单数',
              type: 'line',
              yAxisIndex: 1,
              data: orderCount,
              itemStyle: {
                color: activeStatsTab.value === 'sales' ? '#67C23A' : '#9370DB'
              },
              lineStyle: {
                color: activeStatsTab.value === 'sales' ? '#67C23A' : '#9370DB'
              },
              symbol: 'circle',
              symbolSize: 6
            }
          ]
        }
        chart.setOption(defaultOption)
      } else {
        console.warn('无法获取默认图表数据。')
        chart.setOption({
          title: {
            text: '无数据',
            left: 'center',
            top: 'center',
            textStyle: {
              color: '#999',
              fontSize: 20
            }
          }
        })
      }
    } catch (fallbackError) {
      console.error('使用默认数据失败:', fallbackError)
    }
  }
}

onMounted(async () => {
  // 加载控制台数据
  await loadDashboardData()

  // 在数据加载完成后再初始化图表
  initChart()
})

// 监听数据变化，更新图表
watch(coreMetrics, () => {
  if (chart) {
    updateChart()
  }
})

// 监听状态变化，更新图表
watch([activeStatsTab, activeTimeRange], () => {
  updateChart()
})

// 组件卸载时清理资源
onUnmounted(() => {
  stopAutoRefresh()
  if (chart) {
    chart.dispose()
    chart = null
  }
})
</script>

<style scoped>
.workbench {
  padding: 24px;
}

.workbench-title {
  font-size: 24px;
  font-weight: bold;
  margin: 0 0 24px 0;
  color: #333;
}

.core-indicators {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  position: relative;
}

.indicators-header {
  position: absolute;
  top: 20px;
  right: 20px;
  color: #666;
  font-size: 14px;
}

.indicators-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-top: 20px;
}

.indicator-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.indicator-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  font-weight: bold;
}

.revenue-icon {
  background-color: #e6f7ff;
  color: #1890ff;
}

.order-icon {
  background-color: #f6ffed;
  color: #52c41a;
}

.collection-icon {
  background-color: #fff7e6;
  color: #fa8c16;
}

.purchase-icon {
  background-color: #f9f0ff;
  color: #722ed1;
}

.purchase-order-icon {
  background-color: #fff2e8;
  color: #fa541c;
}

.payment-icon {
  background-color: #f6ffed;
  color: #52c41a;
}

.approval-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
}

.approval-icon.purchase {
  background-color: #e6f7ff;
  color: #1890ff;
}

.approval-icon.sales {
  background-color: #f6ffed;
  color: #52c41a;
}

.approval-icon.inbound {
  background-color: #e6ffe6;
  color: #52c41a;
}

.approval-icon.outbound {
  background-color: #fffbe6;
  color: #faad14;
}

.approval-icon.invoice {
  background-color: #e6f7ff;
  color: #1890ff;
}

.approval-icon.expense {
  background-color: #fffbe6;
  color: #faad14;
}

.approval-icon.issuance {
  background-color: #e6f7ff;
  color: #1890ff;
}

.approval-icon.requisition {
  background-color: #e6ffe6;
  color: #52c41a;
}

.indicator-content {
  flex: 1;
}

.indicator-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.indicator-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.statistics-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.statistics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.statistics-tabs {
  display: flex;
  gap: 0;
  background-color: #f0f0f0;
  border-radius: 4px;
  padding: 4px;
}

.tab-item {
  padding: 8px 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.tab-item.active {
  background-color: white;
  color: #1890ff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.time-range {
  display: flex;
  gap: 8px;
}

.time-btn {
  background-color: white;
  border: 1px solid #d9d9d9;
  color: #666;
}

.time-btn.active {
  background-color: #1890ff;
  border-color: #1890ff;
  color: white;
}

.chart-container {
  margin-top: 20px;
}

.chart-legend {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-bottom: 20px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 2px;
}

.order-amount-sales {
  background-color: #409EFF;
}

.order-count-sales {
  background-color: #67C23A;
}

.order-amount-purchase {
  background-color: #20B2AA;
}

.order-count-purchase {
  background-color: #9370DB;
}

.chart {
  height: 300px;
  width: 100%;
}

/* 底部区域样式 */
.bottom-sections {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 24px;
}

.left-section,
.right-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin: 0 0 16px 0;
  color: #333;
  border-bottom: 2px solid #1890ff;
  padding-bottom: 8px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header .section-title {
  margin-bottom: 0;
}

.refresh-btn {
  background: #1890ff;
  border: none;
  border-radius: 4px;
  padding: 6px 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.refresh-btn:hover:not(:disabled) {
  background: #40a9ff;
  transform: scale(1.05);
}

.refresh-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.refresh-icon {
  font-size: 14px;
  display: inline-block;
  transition: transform 0.3s ease;
}

.refresh-icon.rotating {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 待审批单据样式 */
.approval-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.approval-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  transition: all 0.3s;
}

.approval-item:hover {
  background-color: #e6f7ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.approval-content {
  flex: 1;
}

.approval-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.approval-count {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 通知公告样式 */
.announcement-table {
  overflow-x: auto;
}

.announcement-table table {
  width: 100%;
  border-collapse: collapse;
}

.announcement-table th,
.announcement-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.announcement-table th {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
}

.announcement-table td {
  color: #666;
}

.announcement-table tr:hover {
  background-color: #f8f9fa;
}

/* 订单交付提醒样式 */
.delivery-reminder-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.reminder-header {
  margin-bottom: 20px;
}

.reminder-tabs {
  display: flex;
  gap: 0;
  background-color: #f0f0f0;
  border-radius: 4px;
  padding: 4px;
}

.reminder-tab {
  padding: 8px 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
  font-size: 14px;
}

.reminder-tab.active {
  background-color: white;
  color: #1890ff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.reminder-tab:hover:not(.active) {
  background-color: #e0e0e0;
}

.reminder-table {
  overflow-x: auto;
}

.reminder-table table {
  width: 100%;
  border-collapse: collapse;
}

.reminder-table th,
.reminder-table td {
  padding: 12px 8px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.reminder-table th {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.reminder-table td {
  color: #666;
  font-size: 14px;
}

.reminder-table tr:hover {
  background-color: #f8f9fa;
}

/* 加载状态样式 */
.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  text-align: center;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

.loading-text {
  color: #666;
  font-size: 14px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .bottom-sections {
    grid-template-columns: 1fr;
  }

  .approval-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .approval-grid {
    grid-template-columns: 1fr;
  }

  .indicators-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .statistics-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}
</style> 